/**
 * Created by wang on 2015-10-14.
 * 购买按钮
 */
define(['angular'], function (angular) {
    "use strict";

    var directive = function ($state,$ionicHistory,CommonService, WebService, LocalCacheService) {
        return {
            restrict: "A",
            link: function( scope, element, attrs) {
                element.bind( "click", function() {
                    if(typeof Messenger != 'undefined') {
                        Messenger.sendMsg("ym_event",{eventID:'buy', attributes:
                        {prodCode:attrs["prodCode"],prodSource:attrs["prodSource"],add:attrs["add"]}
                        } ,null,null);
                    }
                    goBuyHtml(attrs["prodCode"], attrs["prodSource"], attrs["add"]);
                });
            }
        }

        function goBuyHtml(prodCode, prodSource, add) { //跳转购买页面
            var type = "pay_trade";
            if (prodSource == 0 || prodSource == 1) {
                type = "pay_trade";
            } else if (prodSource == 2) {
                type = "deposit_trade";
            }
            WebService.getNotice(type).then(function (notice) {
                if (notice.error_no == 0) {
                    if (notice.title && notice.content) {
                        CommonService.showNotice(notice.title + "&&" + notice.content);
                    } else {
                        LocalCacheService.remove("BuyCtrl_buy");
                        LocalCacheService.set("buy_state",
                            {stateName : "trade-buy", stateParams : {prodCode:prodCode, prodSource: prodSource,add: add}});
                        if(!LocalCacheService.getUser()) {
                            $state.go("login",{from: $ionicHistory.currentView().stateName,
                                fromParams: angular.toJson($ionicHistory.currentView().stateParams),
                                w:'notLogin',to: "trade-buy", toParams: angular.toJson({prodCode:prodCode, prodSource: prodSource,add: add})});
                        } else {
                            $state.go("trade-buy",{prodCode:prodCode, prodSource: prodSource,add: add});
                        }
                    }
                }
            });
        }
    };

    directive.$inject = ['$state','$ionicHistory','CommonService', 'WebService', 'LocalCacheService'];
    return directive;
});